# coding: utf-8

import json
import tenjin
import string
from tenjin.helpers import *
from tenjin.escaped import is_escaped, as_escaped, to_escaped


import os
import shutil  

import sys
import mimetypes


baseDataTypes = ["int","long","double","float","Integer","Long","Double","Float","boolean","Boolean","String","Date","Datetime","List","Map","Set"]

''' 将字符串首字大写,其它不变
'''
def upperFirst(a):
	return a[0].capitalize()+(a[1:len(a)])
    
''' 扫描所有模型,将模型定义加载到内存中,为了解决实体类之间的继承时方便引用
'''
models = {}

'''将包名转化为目录名
'''
def transformDirs(packageName):
	dirs = ""
	#print packageName
	array1= packageName.split(".")
	dirs = '/'.join(array1)
	return dirs

'''判定该自定义类是否是自关联/树形结构
'''
def isTree(dataType):
	result = False
	mymodel =  models[dataType]
	myproperties =  mymodel["properties"]
	for myproperty in myproperties:
		if myproperty["dataType"] == dataType:
			result = True
			break
	return result



'''生成代码
'''
def generate(modelpath,templatepath,targetpath):
	
	os.mkdir("temp")

	model = os.listdir(modelpath)  
#所有模型加载到内存,形成一个models的字典
	for m in model:
		input = open(modelpath+"/"+m,"r")
		astr = input.read()
		context = json.loads(astr)
		# 为部分的属性添加缺省值
		ps = context["properties"]
		for p in ps:
			p.setdefault("inSearch",True)
			p.setdefault("inTable",True)
			p.setdefault("ui","")

		models[context["name"]] = context

	
	for m in model:
		print "开始处理模型"+m
		input = open(modelpath+"/"+m,"r")
		astr = input.read()
		context = json.loads(astr)
		# 为部分的属性添加缺省值
		ps = context["properties"]
		for p in ps:
			p.setdefault("inSearch",True)
			p.setdefault("inTable",True)
			p.setdefault("ui","")
        

		context["dir"] = transformDirs(basePackage+"."+context["subPackage"])
		scanDirFile(templatepath,targetpath,context)
	
	os.rmdir("temp")
	

		
'''扫描模板主目录,将所有目录与文件处理
'''
def scanDirFile(templatepath,targetpath,context):
	
	#模板所在主目录
	dirs = os.listdir(templatepath)
	for p in  dirs:
		p1 = templatepath+"/"+p
		p2 = targetpath+"/"+p
		if os.path.isfile(p1):
			

			if not p.endswith("cache"):
				#print u"正在处理文件："+p1+"..."
				generateFile(p1,p2,context)

		elif os.path.isdir(p1):
			#print u"正在处理目录："+p1+"..."
			generateDir(p1,p2,context)
			#print u"递归..."
			scanDirFile(p1,p2,context) #递归处理子目录及文件

def generateDir(templatepath,targetpath,context):
	
	tempfile = open("temp/dirname.tmp","w") # dirs.tmp 记录了当前路径的名称,由于tenjin不支持字符串模板,只好先把目录或文件的名称放在这个临时文件中y
	tempfile.write(targetpath)
	#print "将targetpath的内容"+targetpath+"写入"
	tempfile.close()
	tempfile = open("temp/dirname.tmp","r")
	#print tempfile.read()
	engine = tenjin.SafeEngine(cache=tenjin.MemoryCacheStorage())
	dirname = engine.render("temp/dirname.tmp",context)
	#print targetpath
	#print dirname
	if not os.path.exists(dirname):
		os.makedirs(dirname)
	os.remove("temp/dirname.tmp")
	


def generateFile(templatepath,targetpath,context):

	
	tempfile = open("temp/filename.tmp","w") # dirs.tmp 记录了当前路径的名称,由于tenjin不支持字符串模板,只好先把目录或文件的名称放在这个临时文件中y
	tempfile.write(targetpath)
	tempfile.close()
	engine = tenjin.SafeEngine(cache=tenjin.MemoryCacheStorage())
	filename = engine.render("temp/filename.tmp",context)



	# 如果文件为二进制文件，则不做解析处理，直接复制

	mime = mimetypes.guess_type(templatepath)
	#print mime[0]



	if  mime[0] != None  and  not mime[0].startswith("image") and os.path.getsize(templatepath) > 0  or mime[0] == None and (templatepath.find("gradle") > 0 or templatepath.find("properties") >0 ):
	

		targetfile = open(filename,"w")
		engine = tenjin.SafeEngine()
		code = engine.render(templatepath,context)   
		targetfile.write(code) 
		
	else:
		
		open(filename, "wb").write(open(templatepath, "rb").read()) 
		


	os.remove("temp/filename.tmp")
	
	

# 执行生成

modelpath = "model"
templatepath = "template"
targetpath = "target"


project = sys.argv[1]
#print(project)
print "获取项目"+project+"的信息..."

input = open(modelpath+"/"+project+"/project.json","r")
astr = input.read()
context = json.loads(astr)

template = context['template']
basePackage = context['basePackage']
version =  context["version"]
database_url =  context["database_url"]
database_user =  context["database_user"]
database_password =  context["database_password"]

print "template:"+template
print "basePackage:"+ basePackage
print "version:"+ version
print "database_url:"+ database_url
print "database_user:"+ database_user
print "database_password:"+ database_password



if not os.path.exists(targetpath):
    os.mkdir(targetpath)

if os.path.exists(targetpath+"/"+project):
	shutil.rmtree(targetpath+"/"+project)

os.mkdir(targetpath+"/"+project)

if os.path.exists("temp"):
	shutil.rmtree("temp")




generate(modelpath+"/"+project+"/entity",templatepath+"/"+template,targetpath+"/"+project)






